package com.xuecheng.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.feignclient.checkcode.CheckCodeClient;
import com.xuecheng.auth.mapper.XcUserMapper;
import com.xuecheng.auth.model.dto.AuthParamsDto;
import com.xuecheng.auth.model.dto.XcUserExt;
import com.xuecheng.auth.model.po.XcUser;
import com.xuecheng.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 账号密码认证
 */
@Slf4j
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    CheckCodeClient checkCodeClient;

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //首先校验验证码是否正确
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();
        if(StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)){
            throw new RuntimeException("验证码为空");

        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if(!verify){
            log.error("验证码错误");
            throw new RuntimeException("验证码错误");
        }
        String username = authParamsDto.getUsername();
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>()
                .eq(XcUser::getUsername,username));
        if(xcUser == null){
            throw new RuntimeException("账号不存在");
        }
        String passwordForm = authParamsDto.getPassword();
        String passwordDb = xcUser.getPassword();
        boolean match = passwordEncoder.matches(passwordForm,passwordDb);
        if(!match){
            throw new RuntimeException("密码错误");
        }
        XcUserExt ext = new XcUserExt();
        BeanUtils.copyProperties(xcUser,ext);
        return ext;
    }
}
